In JavaScript, a cookie is a small piece of data stored in the user's browser. Cookies are used to store information such as user preferences, session tokens, and tracking data between browser sessions.
You can set a cookie using the document.cookie property:
username=John – Sets the name-value pair for the cookie.expires=... – Sets the expiration date for the cookie (optional). If not set, the cookie is deleted when the browser is closed.path=/ – Makes the cookie accessible for all paths on the domain (optional).You can read cookies using document.cookie:
To delete a cookie, set the expires date to a past date:
Here's a complete example:
Secure and HttpOnly flags can enhance security but are set on the server side.